package com.nf.health.app.utils;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.text.format.Time;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nf.health.app.MyApplication;
import com.nf.health.app.core.MyGsonBuilder;
import com.nf.health.app.bodyfat.bean.BodyFatInfo;
import com.nf.health.app.models.BralectModel;
import com.nf.health.app.models.UserInfo;

import java.io.IOException;
import java.io.StreamCorruptedException;
import java.util.List;

import cn.bluetools.SleepsData;

public class PreferenceHelper {

    // 会话session
    public static final String NF_USER_SESSION = "NF_USER_SESSION";
    /**
     * 保存的code
     */
    public static final String TOKEN = "NF_USER_INFO";
    /**
     * 新的token
     */
    public static final String ACCESS_TOKEN = "access_token";
    /**
     * 用户名
     */
    public static final String USERNAME = "username";
    // 密码
    public static final String PASSWORD = "password";

    /**
     * 数据页面  引导
     */
    public static final String DATAYINDAO = "datayindao";

    /**
     * 我的页面  引导
     */
    public static final String PERSONALYINDAO = "personalyindao";

    /**
     * 健康管理封面  引导
     */
    public static final String COVERYINDAO = "coveryindao";

    /**
     * 健康管理目录  引导
     */
    public static final String CATALOGUEYINDAO = "catalogueyindao";


    // 密码
    public static final String FASTIN = "fastin";
    /**
     * 引导注册的Token值
     */
    public static final String ORDER_TOKEN = "ordertoken";
    /**
     * 用户类型
     */
    public static final String USERTYPE = "type";
    /**
     * 家庭id
     */
    public static final String FAMILYID = "familyid";
    /**
     * 用户头像
     */
    public static final String USERICON = "usericon";
    /**
     * 用户昵称
     */
    public static final String USERNICK = "usernick";
    /**
     * 真实姓名
     */
    public static final String USERRNAME = "userRname";
    /**
     * 用户生日
     */
    public static final String USER_LOGIN = "user_login";
    /**
     * 用户生日
     */
    public static final String PASS_LOGIN = "pass_login";
    /**
     * 用户生日
     */
    public static final String BIRTHDAY = "birthday";
    /**
     * 用户性别
     */
    public static final String USERSEX = "usersex";
    /**
     * 用户身高
     */
    public static final String USERHEIGHT = "userhight";

    /**
     * 用户健康币
     */
    public static final String HEALTH_MOENY = "healthMoeny";
    /**
     * 用户当前积分
     */
    public static final String GRADE_VALUE = "gradeValue";
    /**
     * 用户当前等级
     */
    public static final String GRADE = "grade";
    /**
     * 用户体重
     */
    public static final String USERWEIGHT = "userweight";
    /**
     * 是否完善了注册信息
     */
    public static final String REGISTER_INFO_COMPLETE = "register_info_complete";
    /**
     * 首界面的hid
     */
    public static final String TYPE_HPID = "com.nf.home.hpid";


    public static final String USERID = "userid";

    public static final String KEY_NAME = "userinfo";

    public static final String ISLOGIN = "isLogin";
    public static final String BLUETOOTH_DEVICE_NAME = "bluetooth_name";
    public static final String BLUETOOTH_DEVICE_ADDRESS = "bluetooth_address";
    public static final String BLUETOOTH_IS_BING = "bluetooth_is_bind";
    public static final String IS24H = "is24h";
    public static final String BLOOD_PRESSUER_NAME = "bloodPressureName";
    public static final String BLOOD_PRESSUER_ADDRESS = "bloodPressureAddress";
    public static final String BLOOD_PRESSUER_IS_BING = "bloodPressureBind";
    public static final String BLOOD_SUGAR_NAME = "bloodSugarName";
    public static final String BLOOD_SUGAR_ADDRESS = "bloodSugarAddress";
    public static final String BLOOD_SUGAR_IS_BING = "bloodSugarBind";
    public static final String TEMPERATURE_NAME = "temperature_name";
    public static final String TEMPERATURE_ADDRESS = "temperature_address";
    public static final String TEMPERATURE_IS_BING = "temperature_is_bing";
    public static final String TEMPERATURE_LATEST_DATA = "temperature_latest_data";
    public static final String URINE_IS_BING = "urineBind";
    public static final String URINE_ADDRESS = "urineAddress";
    public static final String URINE_NAME = "urineName";
    public static final String BALANCE_IS_BING = "balanceBind";
    public static final String BALANCE_ADDRESS = "balanceAddress";
    public static final String BALANCE_NAME = "balanceeName";
    public static final String BLOOD_PRESSURE_MEASURED_INFO = "blood_pressure_measured_info";
    public static final String URINE_TEST_MEASURED_INFO = "urine_test_measured_info";
    public static final String BLOOD_SUGAR_MEASURED_TIME = "blood_sugar_measured_time";
    public static final String BLOOD_SUGAR_MEASURED_VALUE = "blood_sugar_measured_value";
    public static final String SWEAT_NANLYZER_ADDRESS_ONE = "sweatAnalyzerNAddressUP";
    public static final String SWEAT_NANLYZER_ADDRESS_TWO = "sweatAnalyzerNAddressDown";
    public static final String SWEAT_NANLYZER_FREQUENCY_ONE = "sweat_nanlyzer_frequency_up";
    public static final String SWEAT_NANLYZER_FREQUENCY_TWO = "sweat_nanlyzer_frequency_down";

    /**********
     * 存储血痒仪地址
     ******/
    public static final String Oxygen_NAME = "temperature_name";
    public static final String Oxygen_ADDRESS = "temperature_address";
    public static final String Oxygen_IS_BING = "temperature_is_bing";


    private static UserInfo s_User = null;
    private static List<UserInfo> s_User1 = null;
    /**
     * 储存体脂信息对象
     */
    public static final String BODY_FAT_INFO = "body_fat_info";
    public static final String BODY_FAT_LATEST_DATA = "body_fat_latest_data";
    private static BodyFatInfo s_BodyFatInfo = null;
    /**
     * 体脂历史记录被选中的item
     */
    public static final String BODY_FAT_HISTTORY_ITEM = "body_fat_histtory_item";
    /**
     * 尿检历史记录被选中的item
     */
    public static final String URINE_TEST_HISTTORY_ITEM = "urine_test_histtory_item";
    /**
     * 来电
     */
    public static String isCallON = "isCallON";
    /**
     * 未接来电
     */
    public static String isMisCallON = "isMisCallON";
    /**
     * 短信
     */
    public static String isSMSON = "isSMSON";
    /**
     * 邮件
     */
    public static String isEmailON = "isEmailON";
    /**
     * 社交媒体
     */
    public static String isSocialON = "isSocialON";
    /**
     * 日历日程
     */
    public static String iscalendarON = "iscalendarON";
    /**
     * 防丢失
     */
    public static String isAntiLostON = "isAntiLostON";
    /**
     * 是不是第一次上传历史运动数据
     */
    public static String COM_FIRST_UPLOAD_SPORT_DATA = "com.nf.isfirst.upload.sportdata";
    /**
     * 是不是第一次上传历史睡眠数据
     */
    public static String COM_FIRST_UPLOAD_SLEEP_DATA = "com.nf.isfirst.upload.sleepdata";

    /**
     * 省市县
     */
    public static String PROVINCE_KEY = "province";
    public static String CITY_KEY = "city";
    public static String DISTRICT_KEY = "district";

    public static boolean getBoolean(String key, boolean defValue) {

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MyApplication.getInstance());
        return settings.getBoolean(key, defValue);
    }

    public static void putBoolean(String key, boolean value) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MyApplication.getInstance()).edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    public static int getInt(String key, int defValue) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MyApplication.getInstance());
        return settings.getInt(key, defValue);
    }

    public static void putInt(String key, int value) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MyApplication.getInstance()).edit();
        editor.putInt(key, value);
        editor.commit();
    }

    public static long getLong(String key, long defValue) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MyApplication.getInstance());
        return settings.getLong(key, defValue);
    }

    public static void putLong(String key, long value) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MyApplication.getInstance()).edit();
        editor.putLong(key, value);
        editor.commit();
    }

    public static String getString(String key, String defValue) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MyApplication.getInstance());
        return settings.getString(key, defValue);
    }

    public static void putString(String key, String value) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MyApplication.getInstance()).edit();
        editor.putString(key, value);
        editor.commit();
    }

    public static void remove(String key) {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MyApplication.getInstance()).edit();
        editor.remove(key);
        editor.commit();
    }

    public static void registerOnPrefChangeListener(OnSharedPreferenceChangeListener listener) {
        try {
            PreferenceManager.getDefaultSharedPreferences(MyApplication.getInstance()).registerOnSharedPreferenceChangeListener(listener);
        } catch (Exception e) {
            //
        }
    }

    public static void unregisterOnPrefChangeListener(OnSharedPreferenceChangeListener listener) {
        try {
            PreferenceManager.getDefaultSharedPreferences(MyApplication.getInstance()).unregisterOnSharedPreferenceChangeListener(listener);
        } catch (Exception e) {
            //
        }
    }


    /**
     * 序列号用户名和密码，以字符串保存形式保存到本地
     *
     * @param user
     */
    public synchronized static void putUser(UserInfo user) {
        String str = "";
        try {
            str = SerializableUtil.obj2Str(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        putString(KEY_NAME, str);

        s_User = user;
    }
    /**
     * 序列号用户名和密码，以字符串保存形式保存到本地
     *
     * @param user
     */
    public synchronized static void putUser2(List<UserInfo> user) {
        String str = "";
        try {
            str = SerializableUtil.obj2Str(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        putString(KEY_NAME, str);

        s_User1 = user;
    }

    /**
     * 获取用户对象，获取用户名和密码
     *
     * @return
     */
    public synchronized static UserInfo getUser() {

        if (s_User == null) {
            s_User = new UserInfo();
            // 获取序列化的数据
            String str = getString(KEY_NAME, "");
            try {
                Object obj = SerializableUtil.str2Obj(str);
                if (obj != null) {
                    s_User = (UserInfo) obj;
                }
            } catch (StreamCorruptedException e) {
                return s_User;
            } catch (IOException e) {
                return s_User;
            }
        }
        return s_User;
    }

    public synchronized void DeleteUser() {
        putString(KEY_NAME, "");
        s_User = null;
    }

    /**
     * 存储体脂信息对象
     *
     * @param bodyfatinfo
     */
    public synchronized static void putBodyFatInfo(BodyFatInfo bodyfatinfo) {
        String str = "";
        try {
            str = SerializableUtil.obj2Str(bodyfatinfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        putString(BODY_FAT_INFO, str);

        s_BodyFatInfo = bodyfatinfo;
    }

    /**
     * 获取体脂信息对象
     *
     * @return
     */
    public synchronized static BodyFatInfo getBodyFatInfo() {
        if (s_BodyFatInfo == null) {
            s_BodyFatInfo = new BodyFatInfo();
            // 获取序列化的数据
            String str = getString(BODY_FAT_INFO, "");
            try {
                Object obj = SerializableUtil.str2Obj(str);
                if (obj != null) {
                    s_BodyFatInfo = (BodyFatInfo) obj;
                }
            } catch (StreamCorruptedException e) {
                return s_BodyFatInfo;
            } catch (IOException e) {
                return s_BodyFatInfo;
            }
        }
        return s_BodyFatInfo;
    }

    /**
     * 保存手环失败的运动的历史数据
     */
    public static void saveFaildBraceletHistorySporttData(List<BralectModel> list) {
        if (list != null && list.size() != 0) {
            putString("saveFaildBraceletSportHistortData", new Gson().toJson(list));
        }
    }

    /**
     * 清除手环运动的历史数据
     */
    public static void clearFaildBraceletHistySportData() {
        putString("saveFaildBraceletSportHistortData", "");
    }

    /**
     * 获取手环运动的历史数据
     */
    public static List<BralectModel> getFaildBraceletHisrySportData() {
        //List<BralectModel> list = new ArrayList<>();
        List<BralectModel> list = null;
        String data = getString("saveFaildBraceletSportHistortData", "");
        if (!TextUtils.isEmpty(data)) {
            Gson gson = new MyGsonBuilder().createGson();
            list = gson.fromJson(data, new TypeToken<List<BralectModel>>() {
            }.getType());
        }
        return list;
    }

    /**
     * 保存手环失败的运动的历史数据
     */
    public static void saveFaildBraceletHistorySporttData1(List<BralectModel> list) {
        if (list != null && list.size() != 0) {
            putString("saveFaildBraceletSportHistortData1", new Gson().toJson(list));
        }
    }

    /**
     * 清除手环运动的历史数据
     */
    public static void clearFaildBraceletHistySportData1() {
        putString("saveFaildBraceletSportHistortData1", "");
    }

    /**
     * 获取手环运动的历史数据
     */
    public static List<BralectModel> getFaildBraceletHisrySportData1() {
        //List<BralectModel> list = new ArrayList<>();
        List<BralectModel> list = null;
        String data = getString("saveFaildBraceletSportHistortData1", "");
        if (!TextUtils.isEmpty(data)) {
            Gson gson = new MyGsonBuilder().createGson();
            list = gson.fromJson(data, new TypeToken<List<BralectModel>>() {
            }.getType());
        }
        return list;
    }

    /**
     * 保存手环失败的睡眠的历史数据
     */
    public static void saveFaildBraceletSleepData(List<SleepsData> sleepsDatas) {
        if (sleepsDatas != null && sleepsDatas.size() != 0) {
            putString("saveFaildBraceletSportSleepData", new Gson().toJson(sleepsDatas));
        }
    }

    /**
     * 清除手环睡眠的历史数据
     */
    public static void clearFaildBraceletSleepData() {
        putString("saveFaildBraceletSportSleepData", "");
    }

    /**
     * 获取手环睡眠的历史数据
     */
    public static List<SleepsData> getFaildBraceletSleepData() {
        List<SleepsData> list = null;
        String data = getString("saveFaildBraceletSportSleepData", "");
        if (!TextUtils.isEmpty(data)) {
            Gson gson = new MyGsonBuilder().createGson();
            list = gson.fromJson(data, new TypeToken<List<SleepsData>>() {
            }.getType());
        }
        return list;
    }

    /**
     * 保存手环失败的睡眠的历史数据
     */
    public static void saveFaildBraceletSleepData1(List<SleepsData> sleepsDatas) {
        if (sleepsDatas != null && sleepsDatas.size() != 0) {
            putString("saveFaildBraceletSportSleepData1", new Gson().toJson(sleepsDatas));
        }
    }

    /**
     * 清除手环睡眠的历史数据
     */
    public static void clearFaildBraceletSleepData1() {
        putString("saveFaildBraceletSportSleepData1", "");
    }

    /**
     * 获取手环睡眠的历史数据
     */
    public static List<SleepsData> getFaildBraceletSleepData1() {
        List<SleepsData> list = null;
        String data = getString("saveFaildBraceletSportSleepData1", "");
        if (!TextUtils.isEmpty(data)) {
            Gson gson = new MyGsonBuilder().createGson();
            list = gson.fromJson(data, new TypeToken<List<SleepsData>>() {
            }.getType());
        }
        return list;
    }

    /*******
     * 是否一天中第一次上传运动历史数据
     ********/
    public static boolean isFistUploadSportData() {
        boolean isFirstToupload = false;
        //判断是否当天第一次打开
        Time t = new Time();
        t.setToNow();
        final String str = t.year + "-" + (t.month + 1) + "-" + t.monthDay;
        final String nowTime = getString(COM_FIRST_UPLOAD_SPORT_DATA, "");
        if (nowTime.equals(str)) { //TODO 当天第二次进入不提示
            isFirstToupload = true;
        } else {
            isFirstToupload = false;
        }
        return isFirstToupload;
    }

    /*******
     * 向运动历史数据里写入相同的一天
     ********/
    public static void putFistUploadSportData() {
        //判断是否当天第一次打开
        Time t = new Time();
        t.setToNow();
        final String str = t.year + "-" + (t.month + 1) + "-" + t.monthDay;
        putString(COM_FIRST_UPLOAD_SPORT_DATA, str);
    }

    /*******
     * 是否一天中第一次上传睡眠历史数据
     ********/
    public static boolean isFistUploadsleepData() {
        boolean isFirstToupload = false;
        //判断是否当天第一次打开
        Time t = new Time();
        t.setToNow();
        final String str = t.year + "-" + (t.month + 1) + "-" + t.monthDay;
        final String nowTime = getString(COM_FIRST_UPLOAD_SLEEP_DATA, "");
        if (nowTime.equals(str)) { //TODO 当天第二次进入不提示
            isFirstToupload = true;
        } else {
            isFirstToupload = false;
        }
        return isFirstToupload;
    }

    /*******
     * 向运动历史数据里写入相同的一天
     ********/
    public static void putFistUploadSleepData() {
        //判断是否当天第一次打开
        Time t = new Time();
        t.setToNow();
        final String str = t.year + "-" + (t.month + 1) + "-" + t.monthDay;
        putString(COM_FIRST_UPLOAD_SLEEP_DATA, str);
    }

    /**
     * 保存省市区
     * @param province
     */
    public static void saveLocation(String province,String city,String district){
        putString(PROVINCE_KEY,province);
        putString(CITY_KEY,city);
        putString(DISTRICT_KEY,district);
    }

    public static String getProvince(){
        return getString(PROVINCE_KEY,"");
    }

    public static String getCity(){
        return getString(CITY_KEY,"");
    }

    public static String getDistrict(){
        return getString(DISTRICT_KEY,"");
    }

}